const firstLetter = function (str) {
	return str.slice(0, 1).toUpperCase() + str.slice(1);
};
const indexContent = `'use strict';
const {	Router } = require('dx-router-admin');
const config = require('./config.js');					
exports.main = async (event, context) => {										
	//返回数据给客户端
	return new Router(event, context, config).run();
};`;
const configContent = `const init = require('./middleware/init');
const auth = require('./middleware/auth');
const permission = require('./middleware/permission');

module.exports = {
	//应用目录名称
	app_name: 'application',
	// 必选，应用根目录
	app_dir: __dirname,
	//开启调试
	app_debug: true,
	//是否开启多模块
	app_multi_module: true,
	// 默认模块名
	app_module: 'admin',
	// 默认控制器名
	app_controller: 'index',
	// 默认操作名
	app_action: 'index',
	// 统一service 在应用目录下
	app_unify_service: false,
	// 开启多语言
	app_multi_lang: false,
	// 默认语言
	app_lang: 'zh_CN',
	// 允许的语言列表
	app_lang_list: ['zh_CN', 'en_US'],
	// 自定义助手函数 应用目录下创建 helper.js
	app_helper: 'helper',
	//事件配置
	app_hooks: {
		//app_init: 'tags/app_init.js',
	},
	//中间件配置
	app_middleware: [
		[
			init(), //初始化uniId
			{
				name: 'init',
				enable: true,
			},
		],
		[
			auth(), // uniId 校验 token 中间件
			{
				name: 'auth',
				enable: true,
				ignore: [],
			},
		],
		[
			permission(), // uniId 校验权限中间件
			{
				name: 'permission',
				enable: true,
				ignore: [],
			},
		],
	],
};
`;
const initContent = `const uniID = require('uni-id-common');
module.exports = () => {
	// 返回中间件函数
	return async function auth(app, next) {
		app.$dx.uniID = uniID.createInstance({ // 自行创建uni-id实例，传入context，后续均使用此uniID调用相关接口
			context: app.$dx.request.context
		})	
		// 设置当前请求的 auth 对象
		app.$dx.auth = await app.$dx.uniID.checkToken(app.$dx.request.uniIdToken);
		// 执行后续中间件			
		await next(); 
	}
}
`;
const authContent = `module.exports = () => {
	// 返回中间件函数
	return async function auth(app, next) {
		let {
			$dx
		} = app;
		// 校验 token		
		if ($dx.auth.errCode !== 0) {
			// 校验失败，抛出错误信息
			$dx.error($dx.auth.errMsg,null,4001);
		}
		if ($dx.auth.token) {
			$dx.request.token($dx.auth.token);
		}
		if ($dx.auth.tokenExpired) {
			$dx.request.tokenExpired($dx.auth.tokenExpired);
		}
		if($dx.auth.exp){
			$dx.request.tokenExpired($dx.auth.exp * 1000);
		}
		// 执行后续中间件
		await next()
	}
}`;
const permissionContent = `module.exports = () => {
	// 返回中间件函数
	return async function permission(app, next) {
		let {$dx} = app;
		// 获取 当前请求的云函数 + 路径
		const path = $dx.request.functionName +'/'+ $dx.request.url;
		// 校验
		if (!$dx.auth || (!$dx.auth.role.includes('admin') && !$dx.auth.permission.includes(path))) {
			$dx.error('没有权限～', null, 4003);
		}
		await next(); // 执行后续中间件
	}
}`;
//控制器模版
const getControllerContent = function (fileName, params) {
	let ruleTpl = '';
	// 渲染规则
	for (let item of params) {
		if (item.form.rules.includes('required')) {
			if (!!ruleTpl) {
				ruleTpl += `,
				`;
			}
			ruleTpl += `${item.name}: Joi.${item.attrs.type}().required().error(new Error('${item.title}不能为空'))`;
		}
	}
	let tpl = `const { Backend${!!ruleTpl ? ',Joi' : ''} } = require('dx-router-admin');

module.exports = class ${firstLetter(fileName)} extends Backend {
	constructor(ctx) {
		super(ctx);	
		`;
	if (!!ruleTpl) {
		tpl += `this.dto = {
			${ruleTpl}
		};`;
	}
	tpl += `	
	}
};`;
	return tpl;
};
// 实体模版
const getEntityContent = function (tableName, params) {
	let fieldTpl = '';
	for (let item of params) {
		if (!!fieldTpl) {
			fieldTpl += `,
			`;
		}
		fieldTpl += `{
				type: '${item.attrs.type}',
				key: '${item.name}',
				comment: '${item.title}',
			}`;
	}
	let tpl = `module.exports = {
		table: '${tableName}',
		fields: [
			${fieldTpl}
		],
	};
	`;
	return tpl;
};
// service模版
const getServiceContent = function (fileName, isMultiModule) {
	let tpl = `const { Service } = require('dx-router-admin');
const ${fileName}Entity = require('${isMultiModule ? '../../' : '../'}entity/${fileName}.js');

module.exports = class ${firstLetter(fileName)} extends Service {
	constructor(ctx) {
		super(ctx);
		this.entity = ${fileName}Entity;
	}
};`;
	return tpl;
};
// 表格模版
const getTableContent = function (fileName, funcName, menuName, isMultiModule, moduleName, params) {
	let fieldTpl = '';
	for (let item of params) {
		const isSystemField = ['create_date', 'update_date', 'create_time', 'update_time'].includes(item.name);
		fieldTpl += `{
		`;
		fieldTpl += `  label: '${item.title}',
		`;
		fieldTpl += `  field: '${item.name}',
		`;
		if (!isSystemField) {
			if (['dx-array', 'checkbox'].includes(item.type) || (item.type === 'select' && item.form.multiple)) {
				fieldTpl += `  value: ${!item.attrs.value ? '[]' : JSON.stringify(item.attrs.value)},`;
			} else {
				fieldTpl += `  value: ${
					!item.attrs.value && item.attrs.value !== 0 && item.attrs.value !== false
						? "''"
						: item.attrs.type === 'number'
						? Number(item.attrs.value)
						: JSON.stringify(item.attrs.value)
				},`;
			}
		}
		if (isSystemField) {
			fieldTpl += `	
			width: '200px',
			form: false,
			formatter: 'dxFormatDate',
			`;
		} else if (item.type === 'dx-upload') {
			fieldTpl += `				
			render: 'dx-image',
			width: '80px',
			component: {
				name: 'dx-upload',
				props: {
					limit: ${item.form.upload_max || 1},
				}
			},`;
		} else if (item.type === 'number' || item.type === 'textarea') {
			if(item.type === 'number'){
				fieldTpl += `	
				width: '100px',`;
			}else{
				fieldTpl += `	
				visible:false,
				operator:false,`;
			}
			fieldTpl += `
			component: {
				name: 'el-input',
				props: {
					type: '${item.type}',
					placeholder: '请输入${item.title}',
					clearable: ${item.form.clearable},
				}
			},`;
		} else if (['radio', 'checkbox', 'select'].includes(item.type)) {
			fieldTpl += `
			minWidth: '150px',
			component: {
				name: '${item.type === 'radio' ? 'el-radio-group' : item.type === 'checkbox' ? 'el-checkbox-group' : 'el-select'}',
				options: ${JSON.stringify(item.form.options)},
				${item.type === 'select' ? `multiple:${item.form.multiple},` : ''}
			},`;
		} else if (item.type === 'switch') {
			fieldTpl += `
			minWidth: '150px',
			component: {
				name: 'el-switch',				
			},`;
		} else if (['dx-icon-select', 'dx-array', 'dx-city-select', 'dx-tinymce'].includes(item.type)) {
			fieldTpl += `
			visible:false,
			operator:false,
			component: {
				name: '${item.type}',					
			},`;
		} else if (item.type === 'el-input-number') {
			fieldTpl += `
			minWidth: '150px',
			component: {
				name: 'el-input-number',
				props: {
					placeholder: '请输入${item.title}',
					clearable: ${item.form.clearable},
					`;
			if (item.form.min !== '') {
				fieldTpl += `min: ${Number(item.form.min)},
						`;
			}
			if (item.form.max !== '') {
				fieldTpl += `max: ${item.form.max},
						`;
			}
			if (item.form.step !== '') {
				fieldTpl += `step: ${item.form.step},
						`;
			}
			fieldTpl += `
				}
			},`;
		} else if (item.type === 'date') {
			fieldTpl += `
			minWidth: '150px',
			component: {
				name: 'el-date-picker',
				props: {
					type: '${item.form.dateMode}',
					placeholder: '请选择${item.title}',
					clearable: ${item.form.clearable},
				}
			},`;
		} else if (item.type === 'time') {
			fieldTpl += `
			minWidth: '150px',
			component: {
				name: 'el-time-picker',
				props: {
					placeholder: '请选择${item.title}',
					clearable: ${item.form.clearable},
					isRange: ${item.form.isRange},
				}
			},`;
		}
		// 规则
		if (!isSystemField) {
			fieldTpl += `
			rules: [
				`;
			if (item.form.rules.includes('required')) {
				fieldTpl += `{
					required: true,
					message: '${item.title}不能为空',
				}`;
			} else if(item.form.rules.includes('mobile')) {
				fieldTpl += `{
					validator: (rule, value, callback) => {
						if (!/^1[3456789]\\d{9}$/.test(value)) {
							callback(new Error('请输入正确的手机号'));
						} else {
							callback();
						}
					},
				}`;
			} else if(item.form.rules.includes('email')) {
				fieldTpl += `{
					validator: (rule, value, callback) => {
						if (!/^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
							callback(new Error('请输入正确的手机号'));
						} else {
							callback();
						}
					},
				}`;
			}
			fieldTpl += `
			],
			`;
		}
		fieldTpl += `
		},`;
	}

	let tpl = `
<template>
	<view class="dx-body">
		<dx-table ref="table" :header="tableHeader" :tableParams="tableParams"></dx-table>
	</view>
</template>

<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

const tableHeader = reactive({
	tips: '${menuName || fileName}',
});
const tableParams = reactive({
	columnConfig: {
		resizable: true,
	},
	rowConfig: {
		isCurrent: false,
		isHover: true,
		height: 55,
	},
	showOverflow: 'tooltip',
	funcName:'${funcName}',
	urls: {
		index: '${isMultiModule ? moduleName + '/' : ''}${fileName}/index',
		add: '${isMultiModule ? moduleName + '/' : ''}${fileName}/add',
		edit: '${isMultiModule ? moduleName + '/' : ''}${fileName}/edit',
		del: '${isMultiModule ? moduleName + '/' : ''}${fileName}/del',
		multi: '${isMultiModule ? moduleName + '/' : ''}${fileName}/multi',
	},
	columns: [
		{ type: 'checkbox', align: 'center', width: '60px', operator: false },
		{ type: 'seq', field: 'seq', label: '序号', align: 'center', width: '60px', operator: false },
		${fieldTpl}
		{
			type: 'operate',
			field: 'operate',
			label: '操作',
			align: 'center',
			width: '120px',
			fixed: 'right',
			operator: false,
			buttons: ['edit', 'del'],
			permission:[
				'${funcName}/${isMultiModule ? moduleName + '/' : ''}${fileName}/edit',
				'${funcName}/${isMultiModule ? moduleName + '/' : ''}${fileName}/del'
			]
		},
	],
});

const table = ref();
onLoad(() => {
	nextTick(() => {
		// 加载表单数据
		table.value.getTableList();
	});
});
</script>

<style lang="scss"></style>
`;
	return tpl;
};
module.exports = {
	indexContent,
	authContent,
	initContent,
	permissionContent,
	configContent,
	getControllerContent,
	getEntityContent,
	getServiceContent,
	getTableContent,
};
